<?php

use Phalcon\Mvc\Controller;
use Phalcon\Db\Exception as DbException;

class UserController extends Controller {

    /**
     *
     */
    public function indexAction() {
        $usersModel = new UsersModel();
        $usersResultSet = $usersModel->find()->toArray();
	    $columns = $usersModel->getJqxColumns();

	    $this->smarty->assign('users', $usersResultSet);
	    $this->smarty->assign('columns', $columns);

        $this->smarty->display('users/users_list.tpl');
    }

    /**
     *
     */
    public function addAction() {
        if(!$this->request->isPost()) {
            $form = new AddUserForm();
            $elements = $form->getElements();
            $addUserForm = array();
            foreach ($elements as $key => $element) {
                $addUserForm[$key] = array(
                    'label' => $form->label($key),
                    'input' => $form->render($key, array('class' => 'form-control'))
                );
            }
            $this->smarty->assign('addUserForm', $addUserForm);

            $this->smarty->display('users/users_add.tpl');
        } else {
            $postData = $this->request->getPost();
            $usersModel = new UsersModel();

            try {
                foreach ($postData as $key => $val) {
                    $usersModel->$key = $val;
                }
                $usersModel->save();
                $this->response->redirect('/user');
            } catch (DbException $e) {
                $this->smarty->display('error.tpl');
            }

        }
    }

    /**
     * AJAX function show JSON
     * @return string
     */
    public function ajaxAction() {
        if (!$this->request->isAjax()) {
            $this->smarty->display('users/users_ajax.tpl');
        } else {
            $this->view->disable();
            $usersModel = new UsersModel();
	        $dataFields = $usersModel->getJqxDataField();
	        $columns = $usersModel->getJqxColumns();
            $usersResultSet = $usersModel->find()->toArray();

            echo json_encode(
                array(
                    'dataFields'    => $dataFields,
                    'columns'       => $columns,
                    'resultSet'        => $usersResultSet
                )
            );
        }
    }

}